package Client;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.Border;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.xml.ws.handler.MessageContext.Scope;

import Server.Chat_Server;

public class Client_Gui {

	private static Chat_client chatClient;
	public static String userName;
	private String ipAdress;
	private int port;

	private JFrame frameRoom;

	public static JTextArea onlineUsersArea;
	public static JTextArea chatArea;
	public static JTextPane inputTextArea;
	private JButton sendButton;
	private JButton disconnect;
	StyledDocument document;
	Style style;

	public Client_Gui() {
		userName = ConnectClientToServer.getConnectInstance().getUserName().trim();
		Chat_Server.currentUsers.add(userName);
		ipAdress = ConnectClientToServer.getConnectInstance().getIpAddress().trim();
		port = Integer.parseInt(ConnectClientToServer.getConnectInstance().getPort());
		initComponents();
		connectToServer();
	}

	private void connectToServer() {
		try {
			Socket sock = new Socket(ipAdress, port);
			System.out.println("You connected to: " + ipAdress);
			chatClient = new Chat_client(sock);
			PrintWriter out = new PrintWriter(sock.getOutputStream());
			out.println(userName);
			out.flush();
			Thread x = new Thread(chatClient);
			x.start();

		} catch (java.net.ConnectException e) {
			JOptionPane.showMessageDialog(null, "Connection refused");
			System.exit(0);
		} catch (UnknownHostException e) {
			System.out.println(e);
			JOptionPane.showMessageDialog(null, "Server not responding");
			e.printStackTrace();
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void initComponents() {
		frameRoom = new JFrame(userName);
		frameRoom.setName("Chat");
		JPanel panelGui = new JPanel();
		panelGui.setBackground(new Color(0.3f, 0.8f, 0.9f));
		panelGui.setLayout(null);

		JLabel label = new JLabel("Chat room:");
		label.setBounds(5, 10, 80, 25);
		panelGui.add(label);

		disconnect = new JButton(new ImageIcon("Disconnect_button.png"));
		disconnect.setToolTipText("Disconnect");
		disconnect.setBounds(90, 10, 100, 25);
		disconnect.addActionListener(new ActionForDisconnect());
		panelGui.add(disconnect);

		label = new JLabel("Users online:");
		label.setBounds(550, 10, 80, 25);
		panelGui.add(label);

		onlineUsersArea = new JTextArea();
		onlineUsersArea.setEditable(false);
		onlineUsersArea.setLineWrap(false);
		Border blackborder = BorderFactory.createLineBorder(Color.black);
		JScrollPane scrollUsers = new JScrollPane(onlineUsersArea);
		scrollUsers.setBorder(blackborder);
		scrollUsers.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollUsers.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollUsers.setBounds(510, 30, 170, 430);
		panelGui.add(scrollUsers);

		chatArea = new JTextArea();
		chatArea.setEditable(false);
		chatArea.setBackground(Color.WHITE);
		JScrollPane scrollChat = new JScrollPane(chatArea);
		scrollChat.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollChat.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollChat.setBounds(15, 40, 350, 300);
		panelGui.add(scrollChat);

		inputTextArea = new JTextPane();
		inputTextArea.setEditorKit(new StyledEditorKit());
		inputTextArea.addCaretListener(new Smiley());
		JScrollPane scrollInputTextArea = new JScrollPane(inputTextArea);
		scrollInputTextArea.setBorder(blackborder);
		scrollInputTextArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollInputTextArea.setBounds(15, 365, 350, 80);
		panelGui.add(scrollInputTextArea);

		document = inputTextArea.getStyledDocument();
		style = inputTextArea.addStyle("Style", null);
		// add B,I,U,font,color
		JButton bold = new JButton("B");
		bold.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				StyleConstants.setBold(style, true);;
				try {
					document.insertString(document.getLength(), " ", style);
				} catch (BadLocationException e) {
					System.out.println(e);
					e.printStackTrace();
				}
				inputTextArea.requestFocusInWindow();

			}
		});
		bold.setBounds(15, 343, 45, 20);
		panelGui.add(bold);

		JButton italic = new JButton("I");
		italic.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				StyleConstants.setItalic(style, true);
				try {
					document.insertString(document.getLength(), " ", style);
				} catch (BadLocationException e) {
					System.out.println(e);
					e.printStackTrace();
				}
				inputTextArea.requestFocusInWindow();
			}
		});
		italic.setBounds(65, 343, 45, 20);
		panelGui.add(italic);

		JButton under = new JButton("U");
		under.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				StyleConstants.setUnderline(style, true);
				try {
					document.insertString(document.getLength(), " ", style);
				} catch (BadLocationException e) {
					System.out.println(e);
					e.printStackTrace();
				}
				inputTextArea.requestFocusInWindow();

			}
		});
		under.setBounds(115, 343, 45, 20);
		panelGui.add(under);

		JLabel labelSize = new JLabel("Size:");
		labelSize.setBounds(165, 343, 55, 20);
		panelGui.add(labelSize);

		String size[] = { "12", "14", "16", "18", "20" };
		final JComboBox comboSize = new JComboBox(size);
		comboSize.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent ie) {
				int dim = Integer.parseInt((String) comboSize.getSelectedItem());
				StyleConstants.setFontSize(style, dim);
				try {
					document.insertString(document.getLength(), " ", style);
				} catch (BadLocationException e) {
					System.out.println(e);
					e.printStackTrace();
				}
				inputTextArea.requestFocusInWindow();

			}
		});
		comboSize.setBounds(195, 343, 55, 20);
		panelGui.add(comboSize);

		JLabel labelFont = new JLabel("Font:");
		labelFont.setBounds(260, 343, 55, 20);
		panelGui.add(labelFont);

		String font[] = { "Verdana", "Algerion", "Calibri" };
		final JComboBox comboFont = new JComboBox(font);
		comboFont.addItemListener(new ItemListener() {

			@Override
			public void itemStateChanged(ItemEvent ie) {
				String font = (String) comboFont.getSelectedItem();
				StyleConstants.setFontFamily(style, font);
				try {
					document.insertString(document.getLength(), " ", style);
				} catch (BadLocationException e) {
					System.out.println(e);
					e.printStackTrace();
				}
				inputTextArea.requestFocusInWindow();

			}
		});
		comboFont.setBounds(290, 343, 75, 20);
		panelGui.add(comboFont);
		//

		sendButton = new JButton(new ImageIcon("Send_button.png"));
		sendButton.setToolTipText("Send");
		// sendButton.setBorder(blackborder);
		sendButton.addActionListener(new ActionForSendMessage());
		sendButton.setBounds(380, 365, 70, 80);
		panelGui.add(sendButton);

		frameRoom.add(panelGui);
		frameRoom.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frameRoom.setResizable(false);
		frameRoom.setSize(700, 500);
		frameRoom.setVisible(true);
	}

	class ActionForSendMessage implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == sendButton) {
				if (!inputTextArea.getText().equals("")) {
					chatClient.send(inputTextArea.getText());
					inputTextArea.requestFocus();
				}

			}
		}
	}

	class ActionForDisconnect implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == disconnect) {
				try {
					removeUser(userName);
					chatClient.disconnect();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		}
	}
	
	public static void removeUser(String user){
		String[] lines = Client_Gui.onlineUsersArea.getText().split("\\n");
		Client_Gui.onlineUsersArea.setText("");
		
		//ArrayList<String> aux = new ArrayList<String>();
		for(int i = 0; i < lines.length; i++)
			if(!lines[i].equals(user))	
				Client_Gui.onlineUsersArea.append(lines[i]+"\n");
		
	}

}
